<?php
//
// +------------------------------------------------------------------------+
// | Gecko Framework                                                        |
// +------------------------------------------------------------------------+
//
require_once("Gecko/Form/Exception.php");
require_once("Gecko/Form/Field.php");

/**
 * MultiChoiceBox Control to draw table fields
 *
 * @package Gecko.Form.Field;
 * @author Christopher Valderrama <valderrama.christopher@gmail.com>
 * @copyright Copyright (c) 2008
 * @version $Id$v1.0$ 2008
 * @access public
 **/
class Gecko_Form_Field_ChoiceBox extends Gecko_Form_Field {
	/**
	 * The Type of the control
	 *
	 * @var string
	 */
	protected $type = "choicebox";

	/**
	 * Gets the value of the control as a comma separated
	 * list
	 *
	 * @return string
	 */
	public function getValue() {
		$val = parent::getValue();

		return implode(",", $val);
	}

	/**
	 * Returns the RAW Value (The inner Array)
	 *
	 * @return array
	 */
	public function getRawValue() {
		return parent::getValue();
	}

	/**
	 * Returns the HTML Control
	 *
	 * @return string
	 */
	public function getControl() {
		$params = $this->getParams();
		$value = $this->getValue();
		$name = $this->getName();
		$vars = array();
		$template = Gecko_Router::LIBRARY_DIR . "/Assets/Form/Templates/ChoiceBox.php";
		$chTemplate = Gecko_Router::LIBRARY_DIR . "/Assets/Form/Templates/CheckBox.php";
		$choiceTemplate = '<input type="checkbox" name="%s" value="%s" %s/>%s';
		$options = $params['Options'];
		$useKeys = $params['useKeys'];
		$selected = 'checked="checked"';

		$ops = array();
		foreach( $options as $choiceName => $choiceValue ) {
			$chname = ( $useKeys == true ? $choiceName : $choiceValue );
			if( in_array( $choiceName, (array)$value ) ) {
				$sel = $selected;
			} else {
				$sel = "";
			}

			$chVars = array();
			$chVars['name'] = $name;
			$chVars['checkValue'] = "1";
			$chVars['checked'] = $sel;
			$ops[$chname] = Gecko_Template::renderTemplate( $chTemplate, $chVars, true );
		}

		$vars['class'] = $params['className'];
		$vars['options'] = $ops;
		$vars['name'] = $name . "[]"; // Array Nomenclature
		$vars['value'] = $value;
		$vars['columns'] = (!empty($params['columns']) ? $params['columns'] : 2 );

		$html = Gecko_Template::renderTemplate( $template, $vars, true );
		return $html;
	}
}